package top.jidanmian.iot.mqtt;

import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import top.jidanmian.iot.mqtt.persistence.MqttMessageRepository;
import top.jidanmian.iot.mqtt.persistence.MqttReceivedMessage;

@Service
public class MqttService {
    @Resource
    private MqttClientUtils utils;
    @Resource
    private MqttMessageRepository repository;

    public void sendMessage(String topic, String message) {
        if (!topic.isEmpty() && !message.isEmpty()) {
            utils.publish(topic, message);
        }
    }

    public void subscribe(String topic) {
        utils.subscribe(topic);
    }

    public MqttReceivedMessage getMessage(String topic) {
        if (topic.isEmpty()) return new MqttReceivedMessage();
        return repository.findFirstByTopicIgnoreCaseOrderByIdDesc(topic);
    }
}
